package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    public void saveOrUpdate(Employee entity, Long[] ids) {
        if (entity.getId() == null) {
            // 加盐
            Md5Hash md5Hash = new Md5Hash(entity.getPassword(), entity.getName());
            entity.setPassword(md5Hash.toString());
            employeeMapper.insert(entity);
        } else {
            employeeMapper.deleteRelation(entity.getId());// 更新前删除旧关系
            employeeMapper.updateByPrimaryKey(entity);
        }
        if (ids != null) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(entity.getId(), roleId);
            }
        }
    }

    public void delete(Long id) {
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public PageInfo<?> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<?> list = employeeMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    public boolean checkName(String name) {

        return employeeMapper.checkName(name) == null;
    }

    public List<Employee> selectAll() {
        List<Employee> list = employeeMapper.selectAll();
        return list;
    }


}